package fr.lille.inria.adam.lifl.EcoGardeInventory.scrapper;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

public class LoginTask extends HttpAsyncTask<String, Integer> {
	protected final static String authUrl = "http://signature.enm-lille.fr/enlmsig/index.php?cont=login&event=identification";
	protected final static String successUrl = "http://signature.enm-lille.fr/enlmsig/index.php?cont=menu";
	public final static int SUCCES_CODE = 1;
	public final static int IO_ERROR = 2;
	public final static int INPUT_ERROR = 4;
	public final static int FAIL_CODE = 8;
	
	@Override
	protected Integer doInBackground(String... params) {
		// On forge notre requete POST
		final HttpPost logRequest = new HttpPost(authUrl);
		logRequest.addHeader("X-Requested-With", "XMLHttpRequest");
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("USER", params[0]));
		nameValuePairs.add(new BasicNameValuePair("PASS", params[1]));
		HttpEntity e = null;
		try {
			e = new UrlEncodedFormEntity(nameValuePairs);
		} catch (UnsupportedEncodingException e1) {
			return INPUT_ERROR;
		}
		logRequest.setEntity(e);

		
		final HttpResponse postLogResponse = browser.execute(logRequest);
		logRequest.abort(); // Economisons les ressources, seuls les Headers nous interessent
		if (isASuccessfulLogin(postLogResponse)) return SUCCES_CODE;
		else return FAIL_CODE;
	}
	
	/**Lorsque l'on s'identifie avec succes sur le serveur celui 
	 * nous redirige vers successUrl. Cette méthode vérifie cette condition
	 * @param serverResponse
	 * @return
	 */
	public boolean isASuccessfulLogin(HttpResponse serverResponse) {
		final Header hLocation = serverResponse.getFirstHeader("Location");
		return (hLocation!=null && hLocation.getValue().equals(successUrl));
	}
	
	public static String returnCodeToString(final int code) {
		switch (code) {
		case SUCCES_CODE: return "SUCCESS_CODE";
		case IO_ERROR: return "IO_ERROR";
		case INPUT_ERROR: return "INPUT_ERROR";
		case FAIL_CODE: return "FAIL_CODE";
		default: return "UNKNOW";
		}
	}
}
